<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${categoryName} - 运动商城</title>
    <!-- CSS files -->
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/reset.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/font-awesome.min.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/style.css">
</head>
<body>
    <!-- 导航栏 -->
    <jsp:include page="common/header.jsp"/>
    
    <!-- 商品列表 -->
    <div class="container py-5">
        <!-- 面包屑导航 -->
        <nav aria-label="breadcrumb" class="mb-4">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/">首页</a></li>
                <li class="breadcrumb-item active" aria-current="page">${categoryName}</li>
            </ol>
        </nav>
        
        <!-- 筛选器 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="filters">
                        <span class="me-3">排序:</span>
                        <a href="javascript:void(0)" class="filter-link active me-3" data-sort="default">默认</a>
                        <a href="javascript:void(0)" class="filter-link me-3" data-sort="price-asc">价格从低到高</a>
                        <a href="javascript:void(0)" class="filter-link me-3" data-sort="price-desc">价格从高到低</a>
                        <a href="javascript:void(0)" class="filter-link" data-sort="sales">销量</a>
                    </div>
                    <div class="pages">
                        第 <span id="current-page">1</span>/<span id="total-pages">1</span> 页
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="row" id="product-list">
            <c:if test="${empty products}">
                <div class="col-12 text-center py-5">
                    <img src="${pageContext.request.contextPath}/static/images/empty-result.png" alt="没有商品" style="max-width: 200px;">
                    <h4 class="mt-3">抱歉，暂时没有相关商品</h4>
                </div>
            </c:if>
            
            <c:forEach items="${products}" var="product">
                <div class="col-lg-3 col-md-4 col-6 mb-4">
                    <div class="product-card h-100">
                        <a href="${pageContext.request.contextPath}/product/detail/${product.id}">
                            <img src="${not empty product.mainImage ? product.mainImage : pageContext.request.contextPath.concat('/static/images/product-default.jpg')}" alt="${product.name}" class="product-img">
                            <div class="product-info">
                                <h5 class="product-name">${product.name}</h5>
                                <p class="product-subtitle">${product.subtitle}</p>
                                <div class="product-price">¥${product.price}</div>
                            </div>
                        </a>
                        <button class="btn add-to-cart" data-product-id="${product.id}">
                            <i class="fas fa-shopping-cart me-2"></i>加入购物车
                        </button>
                    </div>
                </div>
            </c:forEach>
        </div>
        
        <!-- 分页 -->
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center" id="pagination">
                <li class="page-item disabled">
                    <a class="page-link" href="javascript:void(0)" aria-label="Previous" id="prev-page">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <li class="page-item active"><a class="page-link" href="javascript:void(0)">1</a></li>
                <li class="page-item disabled">
                    <a class="page-link" href="javascript:void(0)" aria-label="Next" id="next-page">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
    
    <!-- 页脚 -->
    <jsp:include page="common/footer.jsp"/>
    
    <!-- JavaScript 文件 -->
    <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/bootstrap.bundle.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/main.js"></script>
    
    <script>
        $(document).ready(function() {
            // 变量定义
            var currentPage = 1;
            var totalPages = ${pages != null ? pages : 1};
            var pageSize = ${pageSize != null ? pageSize : 12};
            var categoryId = ${categoryId};
            var currentSort = 'default';
            
            // 加载商品
            function loadProducts() {
                $.ajax({
                    url: '${pageContext.request.contextPath}/product/api/category/' + categoryId,
                    type: 'GET',
                    data: {
                        pageNum: currentPage,
                        pageSize: pageSize,
                        sort: currentSort
                    },
                    success: function(response) {
                        if (response.success) {
                            const data = response.data;
                            renderProducts(data.list);
                            updatePagination(data.pageNum, data.pages);
                            
                            // 更新当前页和总页数
                            $('#current-page').text(data.pageNum);
                            $('#total-pages').text(data.pages);
                            totalPages = data.pages;
                            currentPage = data.pageNum;
                        } else {
                            alert(response.message || '获取商品列表失败');
                        }
                    },
                    error: function() {
                        alert('获取商品列表失败，请稍后再试');
                    }
                });
            }
            
            // 渲染商品列表
            function renderProducts(products) {
                const $productList = $('#product-list');
                $productList.empty();
                
                if (products.length === 0) {
                    $productList.html(
                        '<div class="col-12 text-center py-5">' +
                        '<img src="${pageContext.request.contextPath}/static/images/empty-result.png" alt="没有商品" style="max-width: 200px;">' +
                        '<h4 class="mt-3">抱歉，暂时没有相关商品</h4>' +
                        '</div>'
                    );
                    return;
                }
                
                for (let i = 0; i < products.length; i++) {
                    const product = products[i];
                    const contextPath = "${pageContext.request.contextPath}";
                    const productImage = product.mainImage || contextPath + "/static/images/product-default.jpg";
                    const productSubtitle = product.subtitle || '';
                    
                    const productHtml = 
                        '<div class="col-lg-3 col-md-4 col-6 mb-4">' +
                        '<div class="product-card h-100">' +
                        '<a href="' + contextPath + '/product/detail/' + product.id + '">' +
                        '<img src="' + productImage + '" alt="' + product.name + '" class="product-img">' +
                        '<div class="product-info">' +
                        '<h5 class="product-name">' + product.name + '</h5>' +
                        '<p class="product-subtitle">' + productSubtitle + '</p>' +
                        '<div class="product-price">¥' + product.price + '</div>' +
                        '</div>' +
                        '</a>' +
                        '<button class="btn add-to-cart" data-product-id="' + product.id + '"><i class="fas fa-shopping-cart me-2"></i>加入购物车</button>' +
                        '</div>' +
                        '</div>';
                    $productList.append(productHtml);
                }
                
                // 初始化加入购物车按钮
                initAddToCartButtons();
            }
            
            // 更新分页
            function updatePagination(currentPage, totalPages) {
                const $pagination = $('#pagination');
                $pagination.empty();
                
                // 分页链接
                let paginationHtml = '';
                
                // 上一页
                let prevDisabled = currentPage === 1 ? 'disabled' : '';
                paginationHtml += `
                    <li class="page-item ${prevDisabled}">
                        <a class="page-link" href="javascript:;" data-page="${currentPage - 1}">上一页</a>
                    </li>
                `;
                
                // 页码链接
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, currentPage + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    let active = i === currentPage ? 'active' : '';
                    paginationHtml += `
                        <li class="page-item ${active}">
                            <a class="page-link" href="javascript:;" data-page="${i}">${i}</a>
                        </li>
                    `;
                }
                
                // 下一页
                let nextDisabled = currentPage === totalPages ? 'disabled' : '';
                paginationHtml += `
                    <li class="page-item ${nextDisabled}">
                        <a class="page-link" href="javascript:;" data-page="${currentPage + 1}">下一页</a>
                    </li>
                `;
                
                $('#pagination').html(paginationHtml);
                
                // 绑定事件
                $('.page-link[data-page]').click(function() {
                    currentPage = parseInt($(this).data('page'));
                    loadProducts();
                });
                
                $('#prev-page').click(function() {
                    if (currentPage > 1) {
                        currentPage--;
                        loadProducts();
                    }
                });
                
                $('#next-page').click(function() {
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadProducts();
                    }
                });
            }
            
            // 绑定排序链接事件
            $('.filter-link').click(function() {
                $('.filter-link').removeClass('active');
                $(this).addClass('active');
                
                currentSort = $(this).data('sort');
                currentPage = 1;
                loadProducts();
            });
            
            // 初始化加入购物车按钮
            function initAddToCartButtons() {
                $('.add-to-cart').click(function() {
                    const productId = $(this).data('product-id');
                    
                    $.ajax({
                        url: '${pageContext.request.contextPath}/cart/add',
                        type: 'POST',
                        data: {
                            productId: productId,
                            quantity: 1
                        },
                        success: function(response) {
                            if (response.success) {
                                alert('已成功加入购物车');
                            } else {
                                alert(response.message || '加入购物车失败');
                            }
                        },
                        error: function() {
                            alert('加入购物车失败，请稍后再试');
                        }
                    });
                });
            }
            
            // 初始加入购物车按钮
            initAddToCartButtons();
        });
    </script>
</body>
</html> 